<?php

namespace app\common\library;

use alipay\aop\AopClient;
use alipay\aop\request\AlipayTradeAppPayRequest;
use app\common\controller\Api;
use app\common\model\integral\Order as IntegralOrder;
use app\common\model\level\Log as ModelLevelLog;
use app\common\model\MoneyLog;
use app\common\model\order\Order;
use app\common\model\ScoreLog;
use app\common\model\User;
use app\common\model\user\Credit;
use app\common\model\user\LevelLog;
use think\Db;
use think\Env;
use think\Log;
use wechatPay\Wxpay;

/**
 * 统一支付接口
 */
class Pay extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];
    protected $config;
    /**
     * 封装统一支付方法
     *
     */
    public static function pay($id, $attach, $userInfo, $pay_type)
    {
        switch ($attach) {
            case 'order':
                $order = Order::get($id);
                $money = $order['pay_fee'];
                $order->pay_type = $pay_type;
                break;
            case 'vip':
                $order = ModelLevelLog::get($id);
                $order->sn = $order->orderid;
    
                $money = $order['payamount'];
                break;
            case 'integral':
                $order = IntegralOrder::get($id);
                $money = $order['pay_fee'];
                break;
        }

        if ($money <= 0) {
            $time = time();
            $order->pay_status = 1;
            $order->paytime = $time;
        } else {
            if ($pay_type == '0') {
                $sdk = Pay::wxpay($order, $attach);
                //微信支付
            } elseif ($pay_type == '1') {
                //微信小程序支付
            
                $jsapi = (new Pay)->minipay($order->sn, $money, $userInfo->openid, $attach);
                $sdk = [
                    'timeStamp' => (string) $jsapi['timeStamp'],
                    'nonceStr' => $jsapi['nonceStr'],
                    'package' => $jsapi['package'],
                    'signType' =>  $jsapi['signType'],
                    'paySign' => $jsapi['paySign'],
                ];
            } elseif ($pay_type == '2') {
                //余额支付
                $sdk =  Pay::yue($order, '');
            } elseif ($pay_type == '3') {
                //支付宝支付
                $sdk = Pay::alipay($order);
            } elseif ($pay_type == '4') {
                //积分支付
                $sdk = Pay::pointPay($order);
            }
        }
        $order->allowField(true)->save();
        return $sdk ?? '';
    }

    /**
     * 积分支付
     *
     */
    private static function pointPay($data, $payPwd = '')
    {

        $user = User::get($data['user_id']);

        if ($data['pay_fee'] > $user->score) {
            exception('积分不足');
        }
        try {
            if ($data['pay_fee'] > 0) {
                ScoreLog::income($user->id, $data['pay_fee'], 2, 200, $data['sn']);
            }
            IntegralOrder::pay_completion($data['sn']);
        } catch (\Exception $e) {
            exception($e->getMessage());
        }
        return true;
    }

    /**
     * 余额支付
     *
     */
    private static function yue($data, $payPwd = '')
    {

        $user = User::get($data['user_id']);
        // if ($user->pay_pwd != md5(md5($payPwd) . 'pcy')) {
        //     exception('支付密码不正确');
        // }

        if ($data['total_fee'] > $user->money) {
            exception('余额不足');
        }

        try {
            if ($data['total_fee'] > 0) {
                MoneyLog::income($user->id, $data['total_fee'], 2, 500, $data['orderid']);
            }
            Order::pay_completion($data['orderid']);
        } catch (\Exception $e) {
            exception($e->getMessage());
        }
        return true;
    }
    /**
     * 支付宝支付
     *
     */
    private static function alipay($data)
    {
        if (Env::get('app.debug') == true) {
            $data['pay_money'] = 0.01;
        }
        $aop = new AopClient();
        $object['out_trade_no'] = $data['sn'];
        $object['total_amount'] = $data['pay_money'];
        $object['subject'] = '订单支付';
        $json = json_encode($object);
        $request = new AlipayTradeAppPayRequest();
        $request->setNotifyUrl(cdnurl('/api/notify/alipayNotify', true));
        $request->setBizContent($json);
        $result = $aop->sdkExecute($request);
        return $result;
    }


    //小程序下单
    public static function minipay($sn, $pay_fee, $openid, $attach = 'order')
    {
        $out_trade_no = $sn;
        $money = $pay_fee;
        if (Env::get('app.debug') == true) {
            $money = 0.01;
        }
        if (empty($out_trade_no)) {
            exception('缺少参数order_sn');
        }
        // 官方提供网址
        $url = "https://api.mch.weixin.qq.com/v3/pay/transactions/jsapi";
        $urlarr = parse_url($url); //拆解为：[scheme=>https,host=>api.mch.weixin.qq.com,path=>/v3/pay/transactions/native]
        $time = time(); //时间戳
        $noncestr = Wxpay::getNonceStr();
        $appid = Env::get('wechat.min_app_id'); //appID
        $mchid = Env::get('wechat.mchid'); //商户ID
        $xlid =  Env::get('wechat.xlid'); //证书序列号
        $data = array();
        $data['appid'] = $appid;
        $data['mchid'] = $mchid;
        $data['attach'] = $attach;
        $data['description'] = '商品描述'; //商品描述
        $data['out_trade_no'] = $out_trade_no; //订单编号，订单号在微信支付里是唯一的
        $data['notify_url'] =  cdnurl('/api/notify/wechatNotify', true); //需根据自己的情况修改回调接口，也可以为空
        $data['amount']['total'] = $money * 100; //金额 单位 分
        $data['scene_info']['payer_client_ip'] = $_SERVER["REMOTE_ADDR"];; //场景ip
        $data['payer']['openid'] = $openid; //openid
        $array = json_encode($data, JSON_UNESCAPED_UNICODE);
        //签名，包含了$data数据、微信指定地址、随机数和时间
        $key = Wxpay::getSign($array, $urlarr['path'], $noncestr, $time);
        $token = sprintf('mchid="%s",serial_no="%s",nonce_str="%s",timestamp="%d",signature="%s"', $mchid, $xlid, $noncestr, $time, $key);
        //头部信息
        $header  = array(
            'Accept: application/json',
            'Content-Type: application/json',
            'User-Agent:*/*',
            'Authorization: WECHATPAY2-SHA256-RSA2048 ' . $token
        );
        $res = Wxpay::curl_post_https($url, $array, $header);

        Log::write('预成功：' . $res);

        $prepay_id = json_decode($res, true)['prepay_id'];
        $paySign = Wxpay::getWechartSign($appid, $time, $noncestr, 'prepay_id=' . $prepay_id);
        $payData = [
            'timeStamp' => (string) $time,
            'nonceStr' => $noncestr,
            'package' => 'prepay_id=' . $prepay_id,
            'signType' => 'RSA',
            'paySign' => $paySign
        ];
        return $payData;
    }
    // php -f D:\phpstudy_pro\WWW\1255\vendor\wechatpay\wechatpay\bin\CertificateDownloader.php -- -k QbyyrkXYWbwSVT3kw3FwBj1xv9b8rLLu -m 1586569011 -f C:\Users\Administrator\Desktop\1586569011_20230628_cert\apiclient_key.pem -s 63005C1EB8FE15AF1EA278F9C3F774D168929FCD -o C:\Users\Administrator\Desktop\1586569011_20230628_cert\
    // 0 1 * * *  /usr/bin/php /www/wwwroot/1214test.ciyuantiaoyue.com/1214-3.0/public/index.php /addons/crontab/autotask/index
    //微信app支付
    private static function wxpay($order,  $attach)
    {
        $out_trade_no = $order['sn'];
        $money = $order['pay_money'];
        if (Env::get('app.debug') == true) {
            $money = 0.01;
        }
        if (empty($out_trade_no)) {
            exception('缺少参数order_sn');
        }
        // 官方提供网址
        $url = "https://api.mch.weixin.qq.com/v3/pay/transactions/app";
        $urlarr = parse_url($url); //拆解为：[scheme=>https,host=>api.mch.weixin.qq.com,path=>/v3/pay/transactions/native]
        $time = time(); //时间戳
        $noncestr = Wxpay::getNonceStr();
        $appid = config('site.app_id'); //appID
        $mchid = config('site.mch_id'); //商户ID
        $xlid =  config('site.serial_no'); //证书序列号
        $data = array();
        $data['appid'] = $appid;
        $data['mchid'] = $mchid;
        $data['attach'] = $attach;
        $data['description'] = '商品描述'; //商品描述
        $data['out_trade_no'] = $out_trade_no; //订单编号，订单号在微信支付里是唯一的
        $data['notify_url'] =  cdnurl('/api/notify/wechatNotify', true); //需根据自己的情况修改回调接口，也可以为空
        $data['amount']['total'] = $money * 100; //金额 单位 分
        $data['scene_info']['payer_client_ip'] = $_SERVER["REMOTE_ADDR"];; //场景ip
        // $data['payer']['openid'] = $openid; //app支付不需要openid
        $data = json_encode($data);

        //签名，包含了$data数据、微信指定地址、随机数和时间
        $key = Wxpay::getSign($data, $urlarr['path'], $noncestr, $time);
        $token = sprintf('mchid="%s",serial_no="%s",nonce_str="%s",timestamp="%d",signature="%s"', $mchid, $xlid, $noncestr, $time, $key);
        //头部信息
        $header  = array(
            'Accept: application/json',
            'Content-Type: application/json',
            'User-Agent:*/*',
            'Authorization: WECHATPAY2-SHA256-RSA2048 ' . $token
        );
        //向微信接口地址提交json格式的$data和header的头部信息，得到返回值
        $res = Wxpay::curl_post_https($url, $data, $header);
        $prepay_id = json_decode($res, true)['prepay_id'];


        $paySign = Wxpay::getWechartSign($appid, $time, $noncestr, $prepay_id);
        $payData = [
            'appid' => $appid,
            'partnerid' => $mchid,
            'prepayid' => $prepay_id,
            'package' => "Sign=WXPay",
            'noncestr' => $noncestr,
            'timestamp' => (string) $time,
            'sign' => $paySign
        ];
        return $payData;
    }
    //会员开通成功
    public static function vipFulfillment($id, $trade_no = null)
    {
        $log = LevelLog::get($id);
        if (!$log) {
            exception('订单不存在');
        }
    }
    //订单支付成功
    public static function orderFulfillment($sn, $trade_no = null)
    {

        try {
            $order = Order::get([
                'status' => 0,
                'sn' => $sn,
            ]);

            if (!$order) {
                exception('订单不存在');
            }

            // $user = User::get($order->user_id);
            // dd($order->distribution == '2');


            // if ($order->distribution == '2') {
            //     $data['status'] = 2;

            //     $data['qh_image'] = build($order->id);
            // }

            $order->transaction_id = $trade_no;
            $order->paytime = time();
            $order->status = '10';
            $order->save();
            // $user->setInc('consumption', $order->pay_money);

        } catch (\Exception $e) {
            exception($e);
        }
    }
}
